package com.gcspring.h2db.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author: guc
 * @Description:
 * @Date: 2022-9-1 10:12
 * @Version: 1.0
 */
@RestController
@RequestMapping("test")
public class TestController {

    @RequestMapping("/")
    public String test() {
        return "success";
    }

    @RequestMapping("/download")
    public ResponseEntity<InputStreamResource> download() throws IOException {
        FileSystemResource file = new FileSystemResource("G:\\资料\\SpringMVC响应用户请求流程.png");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", URLEncoder.encode(file.getFilename(),"utf-8")));
        headers.add("Pragma", "no-cache");
        headers.add("expires", "0");
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()))
                ;
    }
}
